import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:get/get.dart';

import '../../../../model/tag_model.dart';

class ImproveInformationLogic extends GetxController {
  List<TagModel> tagList = [];
  List<TagModel> myTags = [];

  TagModel? selectedFir;
  TagModel? selectedSec;

  bool isSetter = false;

  @override
  void onInit() {
    super.onInit();

    var a = Get.arguments;
    if (a != null) {
      isSetter = a["isSetter"] ?? false;
    }

    loadTagData();
  }

  loadTagData() {
    WhlApi.getMySoul.get({}, withLoading: true).then((value) {
      if (value.isSuccess()) {
        tagList = List<TagModel>.from(
            value.data.map((e) => TagModel.fromJson(e)).toList());
        update();
      }
    });
  }

  saveBaseInfo() {
    var a = Get.arguments;
    if (a != null) {
      Map<String, dynamic> param = a["userInfo"];
      WhlApi.saveUserBaseInfo.post(param, withLoading: true).then((value) {
        if (value.isSuccess()) {
          WhlUserUtils.setUserInfoComplete(true);
          Get.offAllNamed(Routes.main);
        }
      });
    }
  }

  savePassword() {
    var a = Get.arguments;
    print(a);
    if (a != null) {
      Map<String, dynamic> param = a["userInfo"];
      WhlApi.savePassword.post(param).then((value) {
        if (value.isSuccess()) {
          print(value.data);
        }
      });
    }
  }

  saveSexInfo() {
    var a = Get.arguments;
    if (a != null) {
      Map<String, dynamic> param = a["sexParam"];
      WhlApi.saveUserInformation.post(param).then((value) {
        if (value.isSuccess()) {
          print(value.data);
        }
      });
    }
  }

  addTag(TagModel model) {
    if (!myTags.any((m) => m.id == model.id)) {
      myTags.add(model);
    } else {
      myTags.removeWhere((m) => m.id == model.id);
    }
    update();
  }

  bindTag() {
    List allIds = myTags.map((e) => e.id).toList();
    if (allIds.isEmpty) return;
    Map<String, dynamic> param = {"soulIds": allIds};
    WhlApi.bindLHTag.post(param).then((value) {
      if (value.isSuccess()) {
        if (isSetter) {
          MyToast.show("绑定成功");
          Get.back(result: true);
        }
      }
    });
  }

  void confirmAction() {
    if (!isSetter) {
      savePassword();
      saveBaseInfo();
      saveSexInfo();
    }
    bindTag();
  }
}
